package org.arain.baseii.system.sql;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

import org.arain.baseii.utils.ArainResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.Connection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SysSqlServiceImpl implements SysSqlService{
	 @Value("${jdbc.driver}")
	 private  String DRIVER;
	@Value("${jdbc.url}")
	 private  String URL;
	@Value("${jdbc.username}")
	 private  String USERNAME;
	@Value("${jdbc.password}")
	 private  String PASSWORD;
	@Value("${TABLE}")
	private  String table;
	@Override
	public String load_grid() throws Exception{

	    
        Class.forName(DRIVER);
        Connection con = (Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
        DatabaseMetaData metaData = (DatabaseMetaData) con.getMetaData();
        
        /**
         * 1.返回数据库的相关信息
         */
         System.out.println("数据库已知的用户: "+ metaData.getUserName());   
         System.out.println("数据库的系统函数的逗号分隔列表: "+ metaData.getSystemFunctions());   
         System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ metaData.getTimeDateFunctions());   
         System.out.println("数据库的字符串函数的逗号分隔列表: "+ metaData.getStringFunctions());   
         System.out.println("数据库供应商用于 'schema' 的首选术语: "+ metaData.getSchemaTerm());   
         System.out.println("数据库URL: " + metaData.getURL());   
         System.out.println("是否允许只读:" + metaData.isReadOnly());   
         System.out.println("数据库的产品名称:" + metaData.getDatabaseProductName());   
         System.out.println("数据库的版本:" + metaData.getDatabaseProductVersion());   
         System.out.println("驱动程序的名称:" + metaData.getDriverName());   
         System.out.println("驱动程序的版本:" + metaData.getDriverVersion()); 
         System.out.println();   
         System.out.println("数据库中使用的表类型"); 
         
         JSONObject object = new JSONObject();
         object.accumulate("UserName", metaData.getUserName());
         object.accumulate("URL", metaData.getURL());
         object.accumulate("ProductName", metaData.getDatabaseProductName());
         object.accumulate("ProductVersion", metaData.getDatabaseProductVersion());
         object.accumulate("Version",metaData.getDriverVersion());
         
         ResultSet rs = metaData.getTableTypes();   
         while (rs.next()) {   
             System.out.println("1.-->"+rs.getString(1));  
         }   
         rs.close();   
         
         ResultSet rs1 = metaData.getTables(null,table,null, null);   
         object.accumulate("tableName",table);
         while (rs1.next()) {   
             System.out.println();   
             System.out.println("数据库名:"+ rs1.getString(1));   
             System.out.println("表名: "+rs1.getString(3));   
             System.out.println("类型: "+rs1.getString(4));   
             
         }   
         rs1.close();   
         
         JSONArray array = new JSONArray();
         array.add(object);
         JSONObject  out = new JSONObject();
         out.accumulate("total",array.size());
 		 out.accumulate("rows",array);
         return out.toString(); 
		
	}
	@Override
	public ArainResult exportDatabaseTool(String hostIP, String userName, String password, String savePath,
			String fileName, String databaseName) throws InterruptedException{  
        File saveFile = new File(savePath);  
        if (!saveFile.exists()) {// 如果目录不存在  
            saveFile.mkdirs();// 创建文件夹  
        }  
        if(!savePath.endsWith(File.separator)){  
            savePath = savePath + File.separator;  
        }  
          
        PrintWriter printWriter = null;  
        BufferedReader bufferedReader = null;  
        try {  
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));  
            Process process = Runtime.getRuntime().exec(" mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);  
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");  
            bufferedReader = new BufferedReader(inputStreamReader);  
            String line;  
            while((line = bufferedReader.readLine())!= null){  
                printWriter.println(line);  
            }  
            printWriter.flush();  
            if(process.waitFor() == 0){//0 表示线程正常终止。  
                return ArainResult.ok();  
            }  
        }catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (bufferedReader != null) {  
                    bufferedReader.close();  
                }  
                if (printWriter != null) {  
                    printWriter.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return ArainResult.build(400, "系统异常");  
    }
}
